package com.ror.java.se.string;

import java.io.UnsupportedEncodingException;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.util.Arrays;

public class Demo04 {
    public static void main(String[] args) throws UnsupportedEncodingException {
        String s = "你好"; //底层采用UTF-16编码存储

        //环境变量
        System.out.println("defaultCharset=" + Charset.defaultCharset()); //macOS: UTF-8

        //编码
        byte[] codeUtf8 = s.getBytes(); //utf-8
        System.out.println(Arrays.toString(codeUtf8)); //[-28, -67, -96, -27, -91, -67]
        byte[] codeGbk = s.getBytes("gbk");
        System.out.println(Arrays.toString(codeGbk)); //[-60, -29, -70, -61]

        //解码
        String sUtf8_to_Gbk = new String(codeUtf8, "gbk"); //gbk decode utf8!
        System.out.println(sUtf8_to_Gbk); //浣犲ソ
        String sGbk_to_Utf8 = new String(codeGbk, StandardCharsets.UTF_8); //utf8 decode gbk!
        System.out.println(sGbk_to_Utf8); //���
    }
}
